<?php

namespace App\Logging;

use Monolog\Formatter\FormatterInterface;

class BankApiLogFormatter implements FormatterInterface
{
    /**
     * Formats a log record.
     *
     * @param array $record A record to format
     * @return string The formatted record
     */
    public function format(array $record): string
    {
        $context = $record['context'] ?? [];
        $logId = $context['log_id'] ?? 'unknown';
        $module = $context['module'] ?? 'general';
        $operation = $context['operation'] ?? '';
        
        // 基础信息
        $output = sprintf(
            "[%s] [%s] [%s] %s: %s",
            $record['datetime']->format('Y-m-d H:i:s'),
            strtoupper($record['level_name']),
            $logId,
            $module . ($operation ? ":{$operation}" : ''),
            $record['message']
        );
        
        // 添加上下文信息
        $contextData = array_filter($context, function($key) {
            return !in_array($key, ['log_id', 'module', 'operation', 'timestamp']);
        }, ARRAY_FILTER_USE_KEY);
        
        if (!empty($contextData)) {
            $output .= ' ' . json_encode($contextData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        }
        
        return $output . PHP_EOL;
    }

    /**
     * Formats a set of log records.
     *
     * @param array $records A set of records to format
     * @return string The formatted set of records
     */
    public function formatBatch(array $records): string
    {
        $message = '';
        foreach ($records as $record) {
            $message .= $this->format($record);
        }
        return $message;
    }
}